package org.springframework.samples.mvc.fileupload;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mvc.extensions.ajax.AjaxUtils;
import org.springframework.samples.mvc.service.ImageService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/fileupload")
public class FileUploadController {
	@Autowired
	private ServletContext servletContext;
	
	/*
	 * ImageView는 파일 시스템에 있는 이미지 파일을 응답으로 돌려주는 역할을 합니다.
	 * 뒷 부분에서 ImageView 클래스를 작성하게 됩니다.
	 */
	@Resource(name="imageView") 
	ImageView imageView;
	
	@Autowired 
	ImageService imageService;
	
	@ModelAttribute
	public void ajaxAttribute(WebRequest request, Model model) {
		model.addAttribute("ajaxRequest", AjaxUtils.isAjaxRequest(request));
	}

	@RequestMapping(method=RequestMethod.GET)
	public void fileUploadForm() {
		System.out.println("★★★★★ step 1");

        String rootPath = System.getProperty("catalina.home");
        System.out.println("rootPath======="+rootPath);
		
	}

	@RequestMapping(method=RequestMethod.POST)
	public void processUpload(
			@RequestParam MultipartFile[] file, 
			Model model, 
			HttpServletRequest request 
			
			) throws IOException, InterruptedException {
		

        String appPath = request.getServletContext().getRealPath("");
        System.out.println("★★★★★appPath======="+appPath);

        String rootPath = System.getProperty("catalina.home");
        System.out.println("rootPath======="+rootPath);
		
		


		HttpSession session = request.getSession(true);
		ServletContext sc=request.getSession().getServletContext(); 
		System.out.println("★★★★★==="+System.getProperty("os.name"));
		String osName = System.getProperty("os.name");
		
		SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyyMMdd");
		String yyyyMMdd = simpledateformat.format(new Date());
		 
		String usrUploadDir = "upload"+File.separator+yyyyMMdd;
//		System.out.println("★★★★★ usrUploadDir="+usrUploadDir);
		// SAVE PATH
//		String filePath = servletContext.getRealPath(File.separator )+ usrUploadDir+File.separator ;
		
		String filePath = "";
		if (!osName.startsWith("Windows")) {
			filePath = "/var/www/html"+File.separator+usrUploadDir +File.separator;
		}
		else {
//			filePath = "C:\\Development\\workspace-sts-3.6.0.RELEASE\\spring-mvc-showcase\\src\\main\\webapp\\resources"+File.separator+usrUploadDir +File.separator;
			
			/**
			 * 로컬 아파치 Alias 로 파일 접근 하도록 설정 httpd.conf
			 * 
				Alias /upload "C:/Development/upload"
				
				<Directory "C:/Development"> 
				    AllowOverride None                                              
				    Options None                                                    
				    Order allow,deny                                                
				    Allow from all                                                  
				</Directory> 

			 */
			
			filePath = "C:\\Development"+File.separator+usrUploadDir +File.separator;
		}
		System.out.println("★★★★★ filePath="+filePath);
		
		

//        HttpSession session = request.getSession(true);

		ArrayList<String> uploadedFileNames = new ArrayList<String>();
		for (MultipartFile file2:file) {

			// TODO get file info
			boolean isEmpty =file2.isEmpty();
			String fileName = file2.getOriginalFilename();
			long size = file2.getSize();
			String name = file2.getName();
			String type = file2.getContentType();
			byte[] content = file2.getBytes();
			file2.getInputStream();
			
			/**
				// TODO SYSOUT
				System.out.println("isEmpty="+isEmpty);
				System.out.println("fileName="+fileName);
				System.out.println("size (KB)="+size/1024);
				System.out.println("name="+name);
				System.out.println("type="+type);
			 */

			if ("".equalsIgnoreCase(fileName)&&  size ==0) {
				
			}
			else{

				// TODO FILE SAVE
				File newFile = new File(filePath + fileName);
				// 디렉토리가 없을 경우 생성
//				System.out.println("★★★★★ request.getRealPath(File.separator)="+request.getServletContext().getRealPath(File.separator) );
				if(!newFile.exists()) {
					newFile.mkdirs();
				}
				

//				String genId = UUID.randomUUID().toString();
//				System.out.println("★★★★ 같은 이름이 존재할경우 genId =="+genId);
				// 같은 이름이 존재할경우는 어떻게 처리하지? UUID 사용해서 처리해야 하는지?
				file2.transferTo(newFile); 

				
			
				if (!osName.startsWith("Windows")) {
			        String folder = filePath;
			        String cmd = "chmod 777 -R " + folder;
			        Runtime rt = Runtime.getRuntime();
			        Process p = rt.exec(cmd);
			        p.waitFor();
				}
				
		        
				uploadedFileNames.add(fileName);
			}
			


			
		}	// for end..
		
		
		String listString = "";

		for (String s : uploadedFileNames)
		{
		    listString += s + "\t";
		}
		System.out.println("★★★★listString="+listString);
		
		if (uploadedFileNames.size()==0) {

			model.addAttribute("message", "File not found!!! ");
		}
		else{

//			model.addAttribute("message", "File '" + uploadedFileNames.size()  + "' uploaded successfully (uploadedFileNames :"+listString+"---");
			model.addAttribute("message", "File '" + uploadedFileNames.size()  + "' uploaded successfully (uploadedFileNames :"+uploadedFileNames.toString()+"---");
			model.addAttribute("uploadedFileNames", uploadedFileNames);
			
			// 아파치 이미지 링크 주소 가 "/"이걸로 나와야 하므로 
			model.addAttribute("usrUploadDir", usrUploadDir.replace("\\",	"/"));
			model.addAttribute("osName", osName);
		}

		
	}
	
	

	@RequestMapping("/image/{imageId}")
	private ImageView getImage(@PathVariable String imageId, ModelMap modelMap) {
		ImageFile imageFile = imageService.get(imageId);
		
		modelMap.put("imageFile", imageFile);
		
		return imageView;
	}
	@RequestMapping("download")
	private ImageView download(@RequestParam("key")String key,@RequestParam("path")String path, ModelMap modelMap,HttpServletRequest req,HttpServletResponse res) {
		String fullPath = path +File.separator + key;
		System.out.println("★★★★★  fullPath=="+fullPath);
		String userAgent = req.getHeader("User-Agent");
		String originalFileName="한글 .png";
		try {
			
			if (userAgent.indexOf("MSIE 5.5") > -1) { // MS IE 5.5 이하
				res.setHeader("Content-Disposition", "filename=" + URLEncoder.encode(originalFileName, "UTF-8").replaceAll("\\+", "\\ ") + ";");
			} else if (userAgent.indexOf("MSIE") > -1) { // MS IE (보통은 6.x 이상 가정)
				res.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(originalFileName, "UTF-8").replaceAll("\\+", "\\ ") + ";");
			} else if (userAgent.indexOf("Trident") > -1) { // MS IE 11
				res.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(originalFileName, "UTF-8").replaceAll("\\+", "\\ ") + ";");
			} else { // 모질라나 오페라
				res.setHeader("Content-Disposition", "attachment; filename=" + new String(originalFileName.getBytes("euc-kr"), "latin1").replaceAll("\\+", "\\ ") + ";");
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return imageView;
	}
	  
	
}
